﻿using SF.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WeChat.Core.Common;
using WeChat.Core.ExtraCore;

namespace SF.Ucenter.admin.gwxfun
{
    public partial class reply_sends_edit : Web.UI.ManagePage
    {
        private string action = DTEnums.ActionEnum.Add.ToString(); //操作类型
        private int id = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            //取到操作类型
            string _action = DTRequest.GetQueryString("action");
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                this.action = DTEnums.ActionEnum.Edit.ToString();//修改类型
                this.id = DTRequest.GetQueryInt("id");
                if (this.id == 0)
                {
                    JscriptMsg("传输参数不正确！", "back");
                    return;
                }
                if (!new BLL.sf_reply_sends().Exists(this.id))
                {
                    JscriptMsg("推送记录不存在或已被删除！", "back");
                    return;
                }
            }
            if (!Page.IsPostBack)
            {
                bingData();
                if (action == DTEnums.ActionEnum.Edit.ToString()) //修改
                {
                    btnSubmit.Text = "再次推送";
                    ShowInfo(this.id);
                }
            }
        }
        #region 加载当前公众号的客户，非群发时显示出来
        private void bingData() 
        {
            Model.manager mgr = Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
            string busnieseNum = mgr.busnieseNum.ToString();
            string appNum = Session[DTKeys.SESSION_APP_INFO].ToString();
            DataTable dt = new BLL.sf_user_info().GetList("busnieseNum='" + busnieseNum + "' and appNum='" + appNum + "' ").Tables[0];
            cblItem.Items.Clear();
            foreach (DataRow dr in dt.Rows)
            {
                cblItem.Items.Add(new ListItem(dr["nickName"].ToString(), dr["openID"].ToString()));
            }
            if (dt.Rows.Count<=0)
            {
                cblItem.Items.Add(new ListItem("无", ""));
            }
        }
        #endregion

        #region 赋值操作=================================
        private void ShowInfo(int _id)
        {
            BLL.sf_reply_sends replyBll = new BLL.sf_reply_sends();
            Model.sf_reply_sends model = replyBll.GetModel(_id);
            txtKeyWords.Text = model.title;
            ddlCategoryId.SelectedValue = model.msgType.ToString();
            if (model.userType == 0)
            {
                cbIsLock.Checked = true;
            }
            else
            {
                cbIsLock.Checked = false;
                //选中 客户
                string[] users = model.userMsg.Split(',');
                for (int i = 0; i < cblItem.Items.Count; i++)
                {
                    for (int j = 0; j < users.Length; j++)
                    {
                        if (cblItem.Items[i].Value.Equals(users[j]))
                        {
                            cblItem.Items[i].Selected = true;
                        }
                    }
                }
            }
            txtMsgNum.Text = model.msgNum.ToString();
            //判断信息类型
            if (model.msgType == 0)
            {
                txtSeoDescription.Text = model.textMsg;
            }
            else if (model.msgType == 1)
            {
                txtImgUrl.Text = model.uriMsg;
                imgUri.ImageUrl = model.uriMsg;
            }
            else if (model.msgType == 2)
            {
                //拆分存储的图文数据
                string[] imgs = model.uriMsg.Split(',');
                string[] texts = model.textMsg.Split('^');
                txtimg0.Text = imgs[0];
                img0.ImageUrl = imgs[0];
                text0.Text = texts[0];
                if (imgs.Length>1)
                {
                    txtimg1.Text = imgs[1];
                    img1.ImageUrl = imgs[1];
                    text1.Text = texts[1];
                }
                if (imgs.Length > 2)
                {
                    txtimg2.Text = imgs[2];
                    img2.ImageUrl = imgs[2];
                    text2.Text = texts[2];
                }
                if (imgs.Length > 3)
                {
                    txtimg3.Text = imgs[3];
                    img3.ImageUrl = imgs[3];
                    text3.Text = texts[3];
                }
                if (imgs.Length > 4)
                {
                    txtimg4.Text = imgs[4];
                    img4.ImageUrl = imgs[4];
                    text4.Text = texts[4];
                }
            }
            else if (model.msgType == 3)
            {
                txtVoiceUrl.Text = model.uriMsg;
            }
            else if (model.msgType == 4)
            {
                txtVideoUrl.Text = model.uriMsg;
            }        }
        #endregion

        #region 增加操作=================================
        private int DoAdd()
        {
            ChkAdminLevel("reply_sends_list", DTEnums.ActionEnum.Add.ToString()); //检查权限
            int result = -1;
            Model.sf_reply_sends model = new Model.sf_reply_sends();
            BLL.sf_reply_sends sendBll = new BLL.sf_reply_sends();
            //商户 公众号 模版等信息
            Model.manager mgr = Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
            string busnieseNum = mgr.busnieseNum.ToString();
            string appNum = Session[DTKeys.SESSION_APP_INFO].ToString();
            model.busnieseNum = busnieseNum;
            model.appNum = appNum;
            model.addTime = DateTime.Now;
            model.msgType = Convert.ToInt32(ddlCategoryId.SelectedValue);
            model.title = txtKeyWords.Text;
            model.msgNum = 1;

            string users = "";
            //是否群发
            if (cbIsLock.Checked==true)
            {
                //if (sendBll.GetList("busnieseNum='" + busnieseNum + "' and appNum='" + appNum + "' and convert(varchar(10),addTime,120)='convert(varchar(10),getdate(),120)' ").Tables[0].Rows.Count>0)
                //{
                //    return 1;
                //}
                DataTable dt = new BLL.sf_user_info().GetList("busnieseNum='" + busnieseNum + "' and appNum='" + appNum + "' ").Tables[0];
                if (dt.Rows.Count<=0)
                {
                    return 1;
                }
                model.userType = 0;
                foreach (DataRow r in dt.Rows)
                {
                    users += r["openID"] + ",";
                }
            }
            else
            {
                for (int i = 0; i < cblItem.Items.Count; i++)
                {
                    if (cblItem.Items[i].Selected == true)
                    {
                        users += cblItem.Items[i].Value + ",";
                    }
                }
                if (users.Equals(""))
                {
                    return 2;
                }
                model.userType = 1;
            }
            string[] us = users.Substring(0,users.Length-1).Split(',');
            //获取 accesstoken
            IDictionary dict = ConfigurationManager.GetSection("weixinPay") as IDictionary;
            string inf_uri = dict["inf_uri"].ToString();
            string ip_url = dict["ip_url"].ToString();
            string sendmsg_uri = dict["sendmsg_uri"].ToString();
            api.wxpay.WebClient obj = new api.wxpay.WebClient();
            string str = obj.GetHtml(inf_uri + "grant_type=client_credential&appid=" + appNum + "&secret=" + new BLL.sf_appidmanage().GetModel(appNum).appsecret);
            SF.Ucenter.shallWeChat.wxaccesstoken p = api.wxpay.JsonHelper.JsonDeserialize<SF.Ucenter.shallWeChat.wxaccesstoken>(str);
            WeChat.Core.Common.WeChatHttpHelper h = new WeChat.Core.Common.WeChatHttpHelper(sendmsg_uri);
            //消息类型
            if (ddlCategoryId.SelectedValue.Equals("0"))
            {
                //文本消息
                if (txtSeoDescription.Text.Equals(""))
                {
                    return 3;
	            }
                model.textMsg = txtSeoDescription.Text;
                for (int i = 0; i < us.Length; i++)
                {
                    WeChatMessage data = new WeChatTextMessage() { Text = this.txtSeoDescription.Text.Trim(), ToUser = us[i] };
                    var r = h.Post<WeChatBasicRs>(data.ToString(), new FormData { { "access_token", p.access_token } });
                }
                            
            }
            else if (ddlCategoryId.SelectedValue.Equals("1"))
            {
                if (txtImgUrl.Text.Equals(""))
                {
                    return 4;
                }
                model.uriMsg = txtImgUrl.Text;
                //获取媒体文件的mediaId
                RemoteMedia resid = WeChat.Core.ExtraCore.WeChatMediaManager.Default.Upload(new LocalMedia() { MediaPath = Server.MapPath(txtImgUrl.Text), MediaType = Media.Image }, p.access_token);
                //循环推送
                for (int i = 0; i < us.Length; i++)
                {
                    WeChatMessage data = new PushImageMessage()
                    {
                        Image = new PushMsgImageData() { MediaID = resid.MediaID },
                        ToUser = us[i]
                    };
                    var r = h.Post<WeChatBasicRs>(data.ToString(), new FormData { { "access_token", p.access_token } });
                }
            }
            else if (ddlCategoryId.SelectedValue.Equals("2"))
            {
                if (txtimg0.Text.Equals("") || text0.Text.Equals(""))
                {
                    return 5;
                }
                model.msgNum = Convert.ToInt32(txtMsgNum.Text);
                model.uriMsg = txtimg0.Text + "|" + url0.Text + ",";
                model.textMsg = text0.Text + "^";
                if (Convert.ToInt32(txtMsgNum.Text) > 1)
                {
                    if (txtimg1.Text.Equals("") || text1.Text.Equals(""))
                    {
                        return 5;
                    }
                    model.uriMsg += txtimg1.Text + "|" + url1.Text + ",";
                    model.textMsg += text1.Text + "^";
                }
                if (Convert.ToInt32(txtMsgNum.Text) > 2)
                {
                    if (txtimg2.Text.Equals("") || text2.Text.Equals(""))
                    {
                        return 5;
                    }
                    model.uriMsg += txtimg2.Text + "|" + url2.Text + ",";
                    model.textMsg += text2.Text + "^";
                }
                if (Convert.ToInt32(txtMsgNum.Text) > 3)
                {
                    if (txtimg3.Text.Equals("") || text3.Text.Equals(""))
                    {
                        return 5;
                    }
                    model.uriMsg += txtimg3.Text + "|" + url3.Text + ",";
                    model.textMsg += text3.Text + "^";
                }
                if (Convert.ToInt32(txtMsgNum.Text) > 4)
                {
                    if (txtimg4.Text.Equals("") || text4.Text.Equals(""))
                    {
                        return 5;
                    }
                    model.uriMsg += txtimg4.Text + "|" + url4.Text + ",";
                    model.textMsg += text4.Text + "^";
                }
                model.uriMsg = model.uriMsg.Substring(0, model.uriMsg.Length - 1);
                model.textMsg = model.textMsg.Substring(0, model.textMsg.Length - 1);
                string[] uris = model.uriMsg.Split(',');
                string[] texts = model.textMsg.Split('^');
                //图文数  推送
                if (Convert.ToInt32(txtMsgNum.Text) == 5)
                {
                    string[] uri0 = uris[0].Split('|');
                    string[] uri1 = uris[1].Split('|');
                    string[] uri2 = uris[2].Split('|');
                    string[] uri3 = uris[3].Split('|');
                    string[] uri4 = uris[4].Split('|');
                    //循环推送
                    for (int i = 0; i < us.Length; i++)
                    {
                        WeChatMessage data = new PushNewsMessage()
                        {
                            News = new PushMsgNewsData()
                            {
                                Articles = 
                                {
                                    new PushMsgNewsItem()
                                    {
                                     Title = model.title,
                                     Description = texts[0],               
                                     PicUrl = ip_url+uri0[0],
                                     Url = uri0[1]
                                    },
                                    new PushMsgNewsItem()
                                    {
                                     Title = model.title,
                                     Description = texts[1],               
                                     PicUrl = ip_url+uri1[0],
                                     Url = uri1[1]
                                    },
                                    new PushMsgNewsItem()
                                    {
                                     Title = model.title,
                                     Description = texts[2],               
                                     PicUrl = ip_url+uri2[0],
                                     Url = uri2[1]
                                    },
                                    new PushMsgNewsItem()
                                    {
                                     Title = model.title,
                                     Description = texts[3],               
                                     PicUrl = ip_url+uri3[0],
                                     Url = uri3[1]
                                    },
                                    new PushMsgNewsItem()
                                    {
                                     Title = model.title,
                                     Description = texts[4],               
                                     PicUrl = ip_url+uri4[0],
                                     Url = uri4[1]
                                    } 
                                }
                            },
                            ToUser = us[i]
                        };
                        var r = h.Post<WeChatBasicRs>(data.ToString(), new FormData { { "access_token", p.access_token } });
                    }
                }
                else if (Convert.ToInt32(txtMsgNum.Text) == 4)
                {
                    string[] uri0 = uris[0].Split('|');
                    string[] uri1 = uris[1].Split('|');
                    string[] uri2 = uris[2].Split('|');
                    string[] uri3 = uris[3].Split('|');
                    //循环推送
                    for (int i = 0; i < us.Length; i++)
                    {
                        WeChatMessage data = new PushNewsMessage()
                        {
                            News = new PushMsgNewsData()
                            {
                                Articles = 
                                {
                                    new PushMsgNewsItem()
                                    {
                                     Title = model.title,
                                     Description = texts[0],               
                                     PicUrl = ip_url+uri0[0],
                                     Url = uri0[1]
                                    },
                                    new PushMsgNewsItem()
                                    {
                                     Title = model.title,
                                     Description = texts[1],               
                                     PicUrl = ip_url+uri1[0],
                                     Url = uri1[1]
                                    },
                                    new PushMsgNewsItem()
                                    {
                                     Title = model.title,
                                     Description = texts[2],               
                                     PicUrl = ip_url+uri2[0],
                                     Url = uri2[1]
                                    },
                                    new PushMsgNewsItem()
                                    {
                                     Title = model.title,
                                     Description = texts[3],               
                                     PicUrl = ip_url+uri3[0],
                                     Url = uri3[1]
                                    }
                                }
                            },
                            ToUser = us[i]
                        };
                        var r = h.Post<WeChatBasicRs>(data.ToString(), new FormData { { "access_token", p.access_token } });
                    }

                }
                else if (Convert.ToInt32(txtMsgNum.Text) == 3)
                {
                    string[] uri0 = uris[0].Split('|');
                    string[] uri1 = uris[1].Split('|');
                    string[] uri2 = uris[2].Split('|');
                    //循环推送
                    for (int i = 0; i < us.Length; i++)
                    {
                        WeChatMessage data = new PushNewsMessage()
                        {
                            News = new PushMsgNewsData()
                            {
                                Articles = 
                                {
                                    new PushMsgNewsItem()
                                    {
                                     Title = model.title,
                                     Description = texts[0],               
                                     PicUrl = ip_url+uri0[0],
                                     Url = uri0[1]
                                    },
                                    new PushMsgNewsItem()
                                    {
                                     Title = model.title,
                                     Description = texts[1],               
                                     PicUrl = ip_url+uri1[0],
                                     Url = uri1[1]
                                    },
                                    new PushMsgNewsItem()
                                    {
                                     Title = model.title,
                                     Description = texts[2],               
                                     PicUrl = ip_url+uri2[0],
                                     Url = uri2[1]
                                    }
                                }
                            },
                            ToUser = us[i]
                        };
                        var r = h.Post<WeChatBasicRs>(data.ToString(), new FormData { { "access_token", p.access_token } });
                    }
                }
                else if (Convert.ToInt32(txtMsgNum.Text) == 2)
                {
                    string[] uri0 = uris[0].Split('|');
                    string[] uri1 = uris[1].Split('|');
                    //循环推送
                    for (int i = 0; i < us.Length; i++)
                    {
                        WeChatMessage data = new PushNewsMessage()
                        {
                            News = new PushMsgNewsData()
                            {
                                Articles = 
                                {
                                    new PushMsgNewsItem()
                                    {
                                     Title = model.title,
                                     Description = texts[0],               
                                     PicUrl = ip_url+uri0[0],
                                     Url = uri0[1]
                                    },
                                    new PushMsgNewsItem()
                                    {
                                     Title = model.title,
                                     Description = texts[1],               
                                     PicUrl = ip_url+uri1[0],
                                     Url = uri1[1]
                                    }
                                }
                            },
                            ToUser = us[i]
                        };
                        var r = h.Post<WeChatBasicRs>(data.ToString(), new FormData { { "access_token", p.access_token } });
                    }
                }
                else if (Convert.ToInt32(txtMsgNum.Text) == 1)
                {
                    string[] uri0 = uris[0].Split('|');
                    //循环推送
                    for (int i = 0; i < us.Length; i++)
                    {
                        WeChatMessage data = new PushNewsMessage()
                        {
                            News = new PushMsgNewsData()
                            {
                                Articles = 
                                {
                                    new PushMsgNewsItem()
                                    {
                                     Title = model.title,
                                     Description = texts[0],               
                                     PicUrl = ip_url+uri0[0],
                                     Url = uri0[1]
                                    }
                                }
                            },
                            ToUser = us[i]
                        };
                        var r = h.Post<WeChatBasicRs>(data.ToString(), new FormData { { "access_token", p.access_token } });
                    }
                }
            }
            else if (ddlCategoryId.SelectedValue.Equals("3"))
            {
                if (txtVoiceUrl.Text.Equals(""))
                {
                    return 6;
                }
                model.uriMsg = txtVoiceUrl.Text;
                //获取媒体文件的mediaId
                RemoteMedia resid = WeChat.Core.ExtraCore.WeChatMediaManager.Default.Upload(new LocalMedia() { MediaPath = Server.MapPath(txtVoiceUrl.Text), MediaType = Media.Voice }, p.access_token);
                //循环推送
                for (int i = 0; i < us.Length; i++)
                {
                    WeChatMessage data = new PushMusicMessage()
                    {
                        Music = new PushMsgMusicData()
                        {
                            Title = model.title,
                            Description = "",
                            ThumbMediaID = resid.MediaID,
                            MusicUrl = "",
                            HqMusicUrl = ""
                        },
                        ToUser = us[i]
                    };
                    var r = h.Post<WeChatBasicRs>(data.ToString(), new FormData { { "access_token", p.access_token } });
                }
            }
            else if (ddlCategoryId.SelectedValue.Equals("4"))
            {
                if (txtVideoUrl.Text.Equals(""))
                {
                    return 7;
                }
                model.uriMsg = txtVideoUrl.Text;
                //获取媒体文件的mediaId
                RemoteMedia resid = WeChat.Core.ExtraCore.WeChatMediaManager.Default.Upload(new LocalMedia() { MediaPath = Server.MapPath(txtVideoUrl.Text), MediaType = Media.Video }, p.access_token);
                //循环推送
                for (int i = 0; i < us.Length; i++)
                {
                    WeChatMessage data = new PushMusicMessage()
                    {
                        Music = new PushMsgMusicData()
                        {
                            Title = model.title,
                            Description = "",
                            ThumbMediaID = resid.MediaID,
                            MusicUrl = "",
                            HqMusicUrl = ""
                        },
                        ToUser = us[i]
                    };
                    var r = h.Post<WeChatBasicRs>(data.ToString(), new FormData { { "access_token", p.access_token } });
                }

            }
            //微信 群发 或 循环推送消息


            if (sendBll.Add(model) > 0)
            {
                AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "推送信息:" + model.title); //记录日志
                result = 0;
            }
            return result;
        }
        #endregion


        // 提交保存
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            int res = DoAdd();
            ddlCategoryId.SelectedValue = "";
            if (res == -1)
            {
                JscriptMsg("保存过程中发生错误！", "");
                return;
            }
            else if (res == 1)
            {
                JscriptShow("消息提示", "当前公众号无客户！", "");
                return;
            }
            else if (res == 2)
            {
                JscriptShow("消息提示", "请选择需推送的客户！", "");
                return;
            }
            else if (res == 3)
            {
                JscriptShow("消息提示", "请录入需要推送的文本信息！", "");
                return;
            }
            else if (res == 4)
            {
                JscriptShow("消息提示", "请上传需要推送的图片信息！", "");
                return;
            }
            else if (res == 5)
            {
                JscriptShow("消息提示", "请上传需要推送的图文信息！", "");
                return;
            }
            else if (res == 6)
            {
                JscriptShow("消息提示", "请上传需要推送的音频信息！", "");
                return;
            }
            else if (res == 7)
            {
                JscriptShow("消息提示", "请上传需要推送的视频信息！", "");
                return;
            }
            else if (res == 0)
            {
                JscriptMsg("推送消息成功！", "reply_sends_list.aspx");
            }
        }

        //信息类型 选择
        protected void ddlCategoryId_SelectedIndexChanged(object sender, EventArgs e)
        {
            string msbox = "setTimeout(\"showMsgType('" + ddlCategoryId.SelectedValue.ToString() + "')\",1500);";
            ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsLine", msbox, true);
        }

    }
}